import { MessageBox } from 'element-ui';
import Vue from 'vue';
import Util from '../utils';
import chargingApi from './chargingApi';
import logApi from './logApi';
import tabSetApi from './tabSetApi';
import tollRuleApi from './tollRuleApi';
import userApi from './userApi';
import productInfoApi from './productInfoApi'
import productCategoryApi from './productCategoryApi';
import commodityApi from './commodityApi'
import paymentRecords from './paymentRecords';
import tableCategoryApi from './tableCategoryApi';
const vm = new Vue();

const createInterface = arr => {
   let Interface = {};
   arr.forEach(v => {
      Interface[v.name] = (param, config) => {
         return new Promise(resolve => {
            v.type === 'get'
               ? Api.axiosGet({
                  url: v.url + param,
                  getAllData: v.getAllData,
                  ...config
               }).then(res => resolve(res))
               : Api.axiosPost({
                  url: v.url,
                  data: param,
                  getAllData: v.getAllData,
                  ...config
               }).then(res => resolve(res));
         });
      };
   });
   return Interface;
};
const Api = {
   userApi: createInterface(userApi),
   logApi: createInterface(logApi),
   tollRuleApi: createInterface(tollRuleApi),
   tabSetApi: createInterface(tabSetApi),
   chargingApi: createInterface(chargingApi),
   productInfoApi:createInterface(productInfoApi),
   productCategoryApi:createInterface(productCategoryApi),
   commodityApi:createInterface(commodityApi),
   paymentRecords:createInterface(paymentRecords),
   tableCategoryApi:createInterface(tableCategoryApi),
   env() {
      if (process.env.NODE_ENV === 'development') return 'development';
      if (window.location.href.includes('test-')) return 'test';
      return 'production';
   },
   uploadUrl() {
      if (this.env() === 'test')
         return '//test-resource.jetmobo.com/service/resource/upload_file';
      return 'https://resource.jetmobo.com/service/resource/upload_file';
   },
   downloadUrl() {
      if (this.env() === 'development' || this.env() === 'test')
         return '//test-resource.jetmobo.com/service/resource/download';
      return '//resource.jetmobo.com/service/resource/download';
   },
   previewOrigin() {
      if (this.env() === 'development') {
         let arr = window.location.origin.split(':');
         return `${arr[0]}:${arr[1]}:3000`;
      }
      return window.location.origin;
   },
   backData(res, getAllData) {
      if (res.status !== 200) {
         vm.$alert(res.statusText || '网络异常');
         return 'error';
      }
      let result = res.data;
      if (getAllData) return result;
      switch (result.code) {
         case 200: //  成功
            return result.data;
         case 5002: // 用户尚未登录
            MessageBox.alert(result.msg, {
               showClose: false,
               callback: async () => {
                  Util.setSessionStorage('backUrl', window.location.href);
                  MessageBox.close();
                  window.localStorage.removeItem('userInfo');
                  // window.location.href = result.data
                  window.location.href = '/';
               }
            });
            return 'error';
         default:
            // 失败
            MessageBox.alert(result.msg || '服务器异常', {
               showClose: false,
               callback: () => {
                  MessageBox.close();
               }
            });
            // return 'error';
            return result;
      }
   },
   axiosPost(config) {
      return new Promise(resolve => {
         if (config.loadingText) Util.openLoading(config.loadingText);
         vm.$axios
            .post(config.url, config.data)
            .then(res => {
               let backData = this.backData(res, config.getAllData);
               if (backData === 'error') return Util.closeLoading();
               resolve(backData);
               if (config.loadingTime > 0) {
                  setTimeout(() => {
                     Util.closeLoading();
                  }, config.loadingTime);
                  return;
               }
               if (config.loadingText) Util.closeLoading();
            })
            .catch(error => {
               // eslint-disable-line no-unused-vars
               console.log(error);

               Util.closeLoading();
            });
      });
   },
   axiosGet(config) {
      return new Promise(resolve => {
         if (config.loadingText) Util.openLoading(config.loadingText);
         vm.$axios
            .get(config.url)
            .then(res => {
               let backData = this.backData(res, config.getAllData);
               if (backData === 'error') return Util.closeLoading();
               resolve(backData);
               if (config.loadingTime > 0) {
                  setTimeout(() => {
                     Util.closeLoading();
                  }, config.loadingTime);
                  return;
               }
               if (config.loadingText) Util.closeLoading();
            })
            .catch(error => {
               // eslint-disable-line no-unused-vars
               // console.log(error);
            })
            .catch(error => {
               // eslint-disable-line no-unused-vars
               // console.log(error);
               Util.closeLoading();
            });
      });
   },

   /**
    * get请求数据导出
    * @param {String} url 导出路径
    * @param {Object} data  导出参数
    */
   exportDataGet(url, data) {
      if (typeof data !== 'object') {
         return;
      }
      let queryData = '',
         downloadUrl = '';
      for (const [key, value] of Object.entries(data)) {
         if (key === 'sessionId') break;
         queryData += `${key}=${value}&`;
      }
      downloadUrl = url + '?' + queryData.slice(0, -1);
      window.location.href = downloadUrl;
   },
   /**
    * post请求数据导出
    * @param {String} url 导出路径
    * @param {Object} data  导出参数
    */
   exportDataPost(config) {
      if (config.loadingText) Util.openLoading(config.loadingText);
      vm.$axios
         .post(config.url, config.data, { responseType: 'blob' })
         .then(res => {
            if (res.status === 200 && res.data.type !== 'application/json') {
               const aLink = document.createElement('a');
               let blob = new Blob([res.data]);
               aLink.href = URL.createObjectURL(blob);
               aLink.download = config.name;
               aLink.style.display = 'none';
               document.body.appendChild(aLink);
               aLink.click();
               URL.revokeObjectURL(aLink.href);
               document.body.removeChild(aLink);
            } else {
               let reader = new FileReader();
               reader.readAsText(res.data, 'utf-8');
               reader.onload = () => {
                  res.data = JSON.parse(reader.result);
                  this.backData(res, config.getAllData);
               };
            }
            if (config.loadingTime > 0) {
               setTimeout(() => {
                  Util.closeLoading();
               }, config.loadingTime);
            }
            if (config.loadingText) Util.closeLoading();
         });
   }
};

export default Api;
